﻿using System;
using System.Collections.Generic;
using System.Text;
using Belmost4PDA.DatabaseWorkPDA;

namespace Belmost4PDA.Fasade
{
    public class LogRecordDetail
    {
        // -- поля для мапинга
        public string fieldName;
        public string fieldDescr;
        public string valueOld;
        public string valueNew;
        // --
        /// <summary>
        /// Сохраняет запись в таблицу BrLogDet
        /// </summary>
        /// <param name="id">Идентификатор FK на BrLog</param>
        public void Save(string id)
        { 
            // генерировать ID
            string ID = GenNewID();
            // вставить в базу запись
            QueryExec q =new QueryExec();
            //string InsertNew = "insert into BrLogDet values (" + ID +", " + id + ", " + fieldName+ ", "+ fieldDescr+", "+valueOld+", "+valueNew+")";
            string InsertNew = "Insert into Brlogdet (idlogdet, idlog, fieldname, fielddescr, valueold, valuenew) values({0}, {1}, '{2}', '{3}', '{4}', '{5}')";
            //check on sql injection
            valueOld = valueOld.Replace("'", "''");
            valueNew = valueNew.Replace("'", "''");
            if(valueOld.LastIndexOf(',')!=-1)
            valueOld = valueOld.TrimEnd('0');
            valueOld.TrimEnd(',');
            if(valueNew.LastIndexOf(',')!=-1)
            valueNew = valueNew.TrimEnd('0');
            valueNew.TrimEnd(',');
            if (valueOld == "")
                valueOld = "0";
            if (valueNew == "")
                valueNew = "0";
            if(valueNew!=valueOld)
            q.Execute(String.Format(InsertNew, ID, id, fieldName, fieldDescr, valueOld, valueNew));
        }

        /// <summary>
        /// Gets the new ID.
        /// </summary>
        /// <returns></returns>
        private string GenNewID()
        {
            string GetOldId = "select max(idlogdet) as idlogdet from BrLogDet";
            QuerySelect q =new QuerySelect();
            q.Select(GetOldId);
            List<DataRows.DataRows> lst = q.GetRows();
            int NewId = int.Parse(lst[0].FieldByNameDef("idlogdet","0"))+1;
            return NewId.ToString();
        }
    }
}
